package com.niiwoo.civet.trade.service.local.invest;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.rpc.RpcContext;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.niiwoo.activity.stage.dto.request.prize.PrizeAddInterestReqDTO;
import com.niiwoo.activity.stage.dto.request.prize.ProjectRaiseAddInterestReqDTO;
import com.niiwoo.activity.stage.dto.request.prize.SummarizePrizeAmountReqDTO;
import com.niiwoo.activity.stage.dto.request.prize.SummarizeProjectAddInterestAmountReqDTO;
import com.niiwoo.activity.stage.dto.response.prize.InvestorExtraDetailDTO;
import com.niiwoo.activity.stage.dto.response.prize.ProjectAddInterestSummarizeRespDTO;
import com.niiwoo.activity.stage.dto.response.prize.SummarizeAmountRespDTO;
import com.niiwoo.activity.stage.enums.prize.UserPrizeTypeIdEnum;
import com.niiwoo.activity.stage.service.prize.ActivityPrizeDubboService;
import com.niiwoo.civet.account.dto.request.QueryMoneyTotalRequestDTO;
import com.niiwoo.civet.account.dto.request.StatisticUserBillAmountRequestDTO;
import com.niiwoo.civet.account.dto.response.QueryMoneyTotalResponseDTO;
import com.niiwoo.civet.account.dto.response.StatisticUserBillAmountReponseDTO;
import com.niiwoo.civet.account.enums.BillAmountStatisticsEnum;
import com.niiwoo.civet.account.enums.StatisticalUserBillAmountTypeEnum;
import com.niiwoo.civet.account.service.MoneyTotalDubboService;
import com.niiwoo.civet.account.service.NiiwooBillDubboService;
import com.niiwoo.civet.account.service.bill.UserBillStatisticsDubboService;
import com.niiwoo.civet.base.constant.OrgConstant;
import com.niiwoo.civet.trade.dao.entity.*;
import com.niiwoo.civet.trade.dao.mapper.*;
import com.niiwoo.civet.trade.dto.ProjectBorrowerPlanNewDTO;
import com.niiwoo.civet.trade.dto.common.ProjectInvestOrderDTO;
import com.niiwoo.civet.trade.dto.invest.UserRelatedAmountDTO;
import com.niiwoo.civet.trade.dto.invest.UserTodayRelatedAmountDTO;
import com.niiwoo.civet.trade.dto.request.InvestAmountStatisticsRequestDTO;
import com.niiwoo.civet.trade.dto.request.InvestOrderListForActivityRequestDTO;
import com.niiwoo.civet.trade.dto.request.InvestOrderStatusRequestDTO;
import com.niiwoo.civet.trade.dto.request.ProjectBorrowerPlanRequestDTO;
import com.niiwoo.civet.trade.dto.request.intelligenceInvest.IntelligenceProtocolloRequestDTO;
import com.niiwoo.civet.trade.dto.response.*;
import com.niiwoo.civet.trade.enums.*;
import com.niiwoo.civet.trade.enums.FadadaContractTemplateEnum.TemplateTypeEnum;
import com.niiwoo.civet.trade.service.local.creditor.TradableInvestOrderService;
import com.niiwoo.civet.trade.service.local.intelligenceInvest.IntelligenceOrderService;
import com.niiwoo.civet.trade.service.local.plan.BorrowerInvestorRepaymentContext;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.civet.trade.utils.RepaymentUtil;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.civet.user.service.UserBasicInfoDubboService;
import com.niiwoo.tripod.base.plan.RepaymentPlanContext;
import com.niiwoo.tripod.base.plan.support.PeriodUnitEnum;
import com.niiwoo.tripod.base.plan.support.RepaymentPlanDTO;
import com.niiwoo.tripod.base.utils.DateUtils;
import com.niiwoo.tripod.provider.dto.response.PageResponseDTO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by Yijian on 2018/7/5.
 */
@Service
public class InvestOrderService {

    private static final Logger logger = LoggerFactory.getLogger(InvestOrderService.class);

    @Autowired
    private ProjectInvestOrderMapperExt projectInvestOrderMapper;
    @Autowired
    private ProjectInvestorPlanMapperExt projectInvestorPlanMapper;
    @Autowired
    private BorrowerInvestorRepaymentContext borrowerInvestorRepaymentContext;
    @Autowired
    private ProjectMapperExt projectMapper;
    @Autowired
    private RateConfigMapperExt rateConfigMapper;
    @Autowired
    private ProjectContractMapperExt projectContractMapperExt;
    @Autowired
    private CreditorSaleDetailMapperExt creditorSaleDetailMapperExt;
    @Autowired
    private TradableInvestOrderService tradableInvestOrderService;
    @Autowired
    private ReceivePaymentPlanService receivePaymentPlanService;
    @Autowired
    private ProjectBorrowerPlanNewMapperExt projectBorrowerPlanMapper;
    @Autowired
    private ProjectPackageInvestOrderMapperExt projectPackageInvestOrderMapperExt;
    @Autowired
    private ProjectPackageInvestOrderDetailMapperExt projectPackageInvestOrderDetailMapperExt;
    @Autowired
    private RefundOrderDetailMapperExt refundOrderDetailMapperExt;
    @Autowired
    private RefundOrderDetailBizMapperExt refundOrderDetailBizMapperExt;

    @Reference(version = "1.0.0")
    private ActivityPrizeDubboService activityPrizeDubboService;
    @Reference(version = "1.0.0")
    private MoneyTotalDubboService moneyTotalDubboService;
    @Reference(version = "1.0.0")
    private UserBasicInfoDubboService userBasicInfoDubboService;
    @Reference(version = "1.0.0")
    private OrganizationDubboService organizationDubboService;
    @Reference(version = "1.0.0")
    private ProjectDubboService projectDubboService;
    //债权转让协议
    @Value("${h5-creditor-agreement-url}")
    private String creditorAgreementUrl;
    //债权转让风险协议
    @Value("${h5-creditor-risk-agreement-url}")
    private String creditorRiskAgreementUrl;
    //智能投服务协议
    @Value("${h5-intelligenceInvest-agreement-url}")
    private String intelligenceInvestAgreementUrl;
    //智能投风险提示书
    @Value("${h5-intelligenceInvest-risk-url}")
    private String intelligenceInvestRiskUrl;

    @Autowired
    private InvestorCreditorMapperExt investorCreditorMapperExt;

    @Autowired
    private IntelligenceOrderService intelligenceOrderService;

    @Reference(version = "1.0.0")
    private NiiwooBillDubboService niiwooBillDubboService;

    @Reference(version = "1.0.0")
    private UserBillStatisticsDubboService userBillStatisticsDubboService;

    @Deprecated
    public InvestOrderStatisticsResponseDTO queryInvestOrderStatistcs(String userId) {
        logger.info("queryInvestOrderStatistcs userId:{}", userId);
        QueryMoneyTotalRequestDTO moneyTotalRequestDTO = new QueryMoneyTotalRequestDTO();
        moneyTotalRequestDTO.setUserId(userId);
        QueryMoneyTotalResponseDTO dto = moneyTotalDubboService.queryMoneyTotal(moneyTotalRequestDTO);

        List<ProjectInvestOrder> backingInvestOrders = projectInvestOrderMapper.getInvestOrderListByUserId(userId);

        BigDecimal receivedPenaltyFee = BigDecimal.ZERO; // 已收罚息

        if (!backingInvestOrders.isEmpty()) {
            for (ProjectInvestOrder projectInvestOrder : backingInvestOrders) {
                InvestorCreditor investorCreditor = investorCreditorMapperExt.queryInvestorCreditorByInvestOrderId(projectInvestOrder.getId());
                if (investorCreditor != null) {
                    receivedPenaltyFee = receivedPenaltyFee.add(investorCreditor.getReceivedPenaltyFee());
                }
            }
        }
        BigDecimal addInterestCoupons = niiwooBillDubboService.statisticalUserBillAmount(userId, StatisticalUserBillAmountTypeEnum.RAISE_INTEREST_RATE_COUPONS); // 加息券利息
        addInterestCoupons = addInterestCoupons == null ? BigDecimal.ZERO : addInterestCoupons;
        BigDecimal investmentCashback = niiwooBillDubboService.statisticalUserBillAmount(userId, StatisticalUserBillAmountTypeEnum.INVESTMENT_CASHBACK); // 投资返现红包
        investmentCashback = investmentCashback == null ? BigDecimal.ZERO : investmentCashback;
        BigDecimal receivedAddInterest = niiwooBillDubboService.statisticalUserBillAmount(userId, StatisticalUserBillAmountTypeEnum.INVESTMENT_RAISE_INTEREST); // 投资加息
        receivedAddInterest = receivedAddInterest == null ? BigDecimal.ZERO : receivedAddInterest;

        InvestOrderStatisticsResponseDTO responseDTO = new InvestOrderStatisticsResponseDTO();

        responseDTO.setRepayPriInter(dto.getDueInCorpusInterest());

        // 已赚收益=已赚收益+已收加息+投资返现红包+已收罚息
        responseDTO.setEarnedIncome(dto.getInvestIncome().add(addInterestCoupons).add(receivedAddInterest).add(investmentCashback).add(receivedPenaltyFee));
        // 若为回款日当天，则显示为“今日待回款X,XXX.xx元“；待回款金额=当天订单状态为待回款状态总金额；
        //BigDecimal todayReturnMoney = projectInvestorPlanMapper.getTodayReturnMoneyByUserId(userId, new Date());
//        if (todayReturnMoney != null && (todayReturnMoney.compareTo(BigDecimal.ZERO) > 0)) {
//            responseDTO.setTodayReturnMoney(todayReturnMoney);
//        }

        responseDTO.setRecentlyCapital(dto.getDueInCorpus());
        responseDTO.setRecentlyInterest(dto.getDueInInterest());
        responseDTO.setReceivedAddInterest(receivedAddInterest);
        responseDTO.setReceivedInterest(dto.getInvestIncome());
        responseDTO.setReceivedPenaltyFee(receivedPenaltyFee);
        responseDTO.setInvestGiven(addInterestCoupons.add(investmentCashback));
        logger.info("queryInvestOrderStatistcs userId:{}, response:{}", userId, JSON.toJSON(responseDTO));
        return responseDTO;
    }

    public PageResponseDTO<InvestOrderStatusResponseDTO> queryInvestOrderList(InvestOrderStatusRequestDTO requestDTO) {
        logger.info("queryInvestOrderList requestDTO:{}", JSON.toJSON(requestDTO));
        PageResponseDTO<InvestOrderStatusResponseDTO> pageResponseDTO = new PageResponseDTO<>();
        Integer count = projectInvestOrderMapper.getMyInvestOrderCount(requestDTO);
        List<ProjectInvestOrder> investOrders = projectInvestOrderMapper.getMyInvestOrderList(requestDTO);
        List<InvestOrderStatusResponseDTO> responseDTOList = new ArrayList<>();
        if (investOrders.size() > 0) {
            for (ProjectInvestOrder projectInvestOrder : investOrders) {
                Project project = projectMapper.selectByPrimaryKey(projectInvestOrder.getProjectId());
                InvestOrderStatusResponseDTO responseDTO = new InvestOrderStatusResponseDTO();
                responseDTO.setProductType(LoanTypeEnum.SPEED_LOAN.getValue().equals(project.getLoanType()) ? Byte.valueOf("7") : project.getLoanType());
                responseDTO.setIsShowOtherLoanTypeLabel(LoanTypeEnum.OTHER_LOAN.getValue().equals(project.getLoanType()) && ProjectCreditTypeEnum.HOUSE_PROPRIETARY_CERTIFICATE.getType().equals(project.getCreditType()) && Byte.valueOf("0").equals(project.getIsMasterBorrower()));
                // 标记产品类型为 债转标
                if (Byte.valueOf("2").equals(projectInvestOrder.getInvestType())) {
                    responseDTO.setProductType(Byte.valueOf("6"));
                    CreditorSaleDetail creditorSaleDetail = creditorSaleDetailMapperExt.selectByPrimaryKeyAndSaleUserId(projectInvestOrder.getCreditorSaleDetailId(), projectInvestOrder.getCreditorSaleUserId());
                    responseDTO.setRemainingDeadlineMonth(creditorSaleDetail.getRemainingDeadlineMonth() == 0 ? null : creditorSaleDetail.getRemainingDeadlineMonth());
                    responseDTO.setRemainingDeadlineDay(creditorSaleDetail.getRemainingDeadlineDay() - RepaymentUtil.getOverdueDay(creditorSaleDetail.getCreateTime(), projectInvestOrder.getCreateTime()));
                    responseDTO.setRemainingDeadlineDay(responseDTO.getRemainingDeadlineDay() == 0 ? null : responseDTO.getRemainingDeadlineDay());
                } else{
                    responseDTO.setAddRate(project.getActivityRaiseRate());
                }
                responseDTO.setProductTypeDesc(Byte.valueOf("7").equals(responseDTO.getProductType()) ? "极速贷" : LoanTypeEnum.enumOf(responseDTO.getProductType()).getDesc());

                // 头像/昵称: 个人标/企业标，取借款人头像和昵称；债转标，取转让人头像和昵称
                setHeadImgAndNickName(projectInvestOrder, project.getBorrowerType(), responseDTO, null);


                responseDTO.setProjectId(projectInvestOrder.getProjectId());
                // 期限:  个人标/企业标，取借款期限；债转标，取标的转让成交时的剩余期限
                responseDTO.setDeadline(projectInvestOrder.getDeadline());
                responseDTO.setDeadlineUnit(projectInvestOrder.getDeadlineUnit());
                responseDTO.setBorrowRate(projectInvestOrder.getBorrowRate());

                // 投资本金: 投资订单的实际支付金额
                responseDTO.setAmount(projectInvestOrder.getAmount());
                // 预期收益=预期利息+预期加息
                BigDecimal earnings = projectInvestOrder.getInterest().add(projectInvestOrder.getAddInterest());
                responseDTO.setInterest(earnings);
                // 投资时间/取消时间
                if (ProjectInvestOrderEvolutionStatusEnum.CLOSED.getValue().compareTo(projectInvestOrder.getEvolutionStatus()) == 0
                        || ProjectInvestOrderEvolutionStatusEnum.ALL_BACKED.getValue().compareTo(projectInvestOrder.getEvolutionStatus()) == 0
                        || ProjectInvestOrderEvolutionStatusEnum.TRANSFERRED.getValue().compareTo(projectInvestOrder.getEvolutionStatus()) == 0) {
                    responseDTO.setTime(projectInvestOrder.getExpireTime().before(projectInvestOrder.getUpdateTime()) ?  projectInvestOrder.getExpireTime() : projectInvestOrder.getUpdateTime());

                    InvestorCreditor investorCreditor = investorCreditorMapperExt.queryInvestorCreditorByInvestOrderId(projectInvestOrder.getId());
                    if(ProjectInvestOrderEvolutionStatusEnum.ALL_BACKED.getValue().equals(projectInvestOrder.getEvolutionStatus())
                            || ProjectInvestOrderEvolutionStatusEnum.TRANSFERRED.getValue().equals(projectInvestOrder.getEvolutionStatus())){
                        if(ProjectInvestOrderEvolutionStatusEnum.ALL_BACKED.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                            responseDTO.setTime(investorCreditor.getOverTime());
                        } else {
                            responseDTO.setTime(investorCreditor.getTransferTime());
                        }
                        StatisticUserBillAmountRequestDTO statisticUserBillAmountRequestDTO = new StatisticUserBillAmountRequestDTO();
                        List<BillAmountStatisticsEnum> billAmountStatisticsEnums = Arrays.asList(BillAmountStatisticsEnum.ACCEPTED_INTEREST,
                                BillAmountStatisticsEnum.PENALTY_INTEREST,
                                BillAmountStatisticsEnum.PLATFORM_AND_ACTIVITY_INCREASE_INTEREST,
                                BillAmountStatisticsEnum.CARD_AND_REDPACKET_INVEST,
                                BillAmountStatisticsEnum.CARD_INCREASE_INTEREST,
                                BillAmountStatisticsEnum.INVEST_CASHBACK);
                        statisticUserBillAmountRequestDTO.setUserId(projectInvestOrder.getUserId());
                        statisticUserBillAmountRequestDTO.setInvestId(projectInvestOrder.getId());
                        statisticUserBillAmountRequestDTO.setBillAmountStatisticsEnums(billAmountStatisticsEnums);

                        List<StatisticUserBillAmountReponseDTO> receivedStatistic = userBillStatisticsDubboService.statisticUserBillAmounts(statisticUserBillAmountRequestDTO);

                        BigDecimal interest = BigDecimal.ZERO;
                        BigDecimal penaltyFee = BigDecimal.ZERO;
                        BigDecimal platformAddInterest = BigDecimal.ZERO;
                        BigDecimal prizeAddInterest = BigDecimal.ZERO;
                        for (StatisticUserBillAmountReponseDTO statisticUserBillAmountReponseDTO: receivedStatistic) {
                            if(statisticUserBillAmountReponseDTO != null) {
                                if(BillAmountStatisticsEnum.ACCEPTED_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
                                    interest = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
                                }
                                if(BillAmountStatisticsEnum.PLATFORM_AND_ACTIVITY_INCREASE_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
                                    platformAddInterest = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
                                }
                                if(BillAmountStatisticsEnum.PENALTY_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
                                    penaltyFee = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
                                }
                                if(BillAmountStatisticsEnum.CARD_INCREASE_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
                                    prizeAddInterest = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
                                }

                            }
                        }

                        // 已挣收益：预期利息+预期加息
                        responseDTO.setRepayInterest(investorCreditor.getReceivedInterest().add(penaltyFee).add(platformAddInterest).add(prizeAddInterest));
                    } else {
                        responseDTO.setRepayInterest(BigDecimal.ZERO);
                    }

                } else {
                    responseDTO.setTime(projectInvestOrder.getCreateTime());
                }
                responseDTO.setOrderId(projectInvestOrder.getId());
                responseDTO.setStatus(projectInvestOrder.getEvolutionStatus());

                if (ProjectInvestOrderEvolutionStatusEnum.INVESTING.getValue().compareTo(projectInvestOrder.getEvolutionStatus()) == 0) {
                    BigDecimal contractAmount = project.getContractAmount();
                    BigDecimal investedAmount = project.getInvestedAmount();
                    if (contractAmount.compareTo(investedAmount) > 0) {
                        responseDTO.setIsCanInvest((byte) 0);
                    } else {
                        responseDTO.setIsCanInvest((byte) 1);
                    }
                }
                // 已提前结清
                if (Integer.valueOf(ProjectSubStatusEnum.FINISH_ADVANCE.getSubStatus()).equals(project.getSubStatus())
                        && ProjectInvestOrderEvolutionStatusEnum.ALL_BACKED.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                    responseDTO.setStatus((byte) 8);
                }
                // 逾期提示文案
                if (ProjectInvestOrderEvolutionStatusEnum.BACKING_OVERDUE.getValue().equals(projectInvestOrder.getEvolutionStatus())
                        && project.getAdvanceOverdueDays() != null) {
                    String overdueMsg;
                    if (project.getAdvanceOverdueDays() == 0) {
                        overdueMsg = "担保公司将在24小时内代偿当期本息";
                    } else {
                        overdueMsg = "若借款人逾期" + project.getAdvanceOverdueDays() + "天，担保公司将在第" + (project.getAdvanceOverdueDays() + 1) + "天代偿当期本息";
                    }
                    responseDTO.setOverdueMsg(overdueMsg);
                }
                responseDTOList.add(responseDTO);
            }
        }

        pageResponseDTO.setItems(responseDTOList);
        pageResponseDTO.measureTotalPage(count, requestDTO.getPageSize());
        logger.info("queryInvestOrderList pageResponseDTO:{}", JSON.toJSON(pageResponseDTO));
        return pageResponseDTO;
    }

    private void setHeadImgAndNickName(ProjectInvestOrder projectInvestOrder, Byte borrowerType, InvestOrderStatusResponseDTO investOrderStatusResponseDTO, InvestStatusResponseDTO investStatusResponseDTO) {
        if (Byte.valueOf("2").equals(borrowerType)) {
            Optional.ofNullable(investOrderStatusResponseDTO)
                    .ifPresent(resp -> {
                        resp.setIsEnterpriseProject(true);
                    });
            Optional.ofNullable(investStatusResponseDTO)
                    .ifPresent(resp -> {
                        resp.setIsEnterpriseProject(true);
                    });

            Optional.ofNullable(organizationDubboService.getByOrgId(projectInvestOrder.getBorrowUserId()))
                    .ifPresent(simpleOrg -> {
                        Optional.ofNullable(investOrderStatusResponseDTO)
                                .ifPresent(resp -> {
                                    resp.setHeadImg(simpleOrg.getLogo());
                                    resp.setNickName(maskCompanyName(simpleOrg.getOrganizationName()));
                                });
                        Optional.ofNullable(investStatusResponseDTO)
                                .ifPresent(resp -> {
                                    resp.setHeadImg(simpleOrg.getLogo());
                                    resp.setNickName(maskCompanyName(simpleOrg.getOrganizationName()));
                                });
                    });
        } else {
            String userId = Byte.valueOf("2").equals(projectInvestOrder.getInvestType()) ? projectInvestOrder.getCreditorSaleUserId() : projectInvestOrder.getBorrowUserId();
            Optional.ofNullable(userBasicInfoDubboService.selectUserBaseInfo(userId))
                    .ifPresent(user -> {
                        Optional.ofNullable(investOrderStatusResponseDTO)
                                .ifPresent(resp -> {
                                    resp.setHeadImg(user.getHeadImage());
                                    resp.setNickName(user.getNickName());
                                });
                        Optional.ofNullable(investStatusResponseDTO)
                                .ifPresent(resp -> {
                                    resp.setHeadImg(user.getHeadImage());
                                    resp.setNickName(user.getNickName());
                                });
                    });
        }
    }

    public InvestStatusResponseDTO queryInvestOrderDetail(Long projectInvestOrderId) {
        logger.info("queryInvestOrderDetail projectInvestOrderId:{}", projectInvestOrderId);
        InvestStatusResponseDTO responseDTO = new InvestStatusResponseDTO();
        // 投资订单
        ProjectInvestOrder projectInvestOrder = projectInvestOrderMapper.selectByPrimaryKey(projectInvestOrderId);
        if (projectInvestOrder != null) {
            Project project = projectMapper.selectByPrimaryKey(projectInvestOrder.getProjectId());
            responseDTO.setOrderId(projectInvestOrder.getId());
            responseDTO.setProjectId(projectInvestOrder.getProjectId());
            responseDTO.setInvestType(projectInvestOrder.getInvestType());
            responseDTO.setProductType(LoanTypeEnum.SPEED_LOAN.getValue().equals(project.getLoanType()) ? Byte.valueOf("7") : project.getLoanType());
            responseDTO.setIsShowOtherLoanTypeLabel(LoanTypeEnum.OTHER_LOAN.getValue().equals(project.getLoanType()) && ProjectCreditTypeEnum.HOUSE_PROPRIETARY_CERTIFICATE.getType().equals(project.getCreditType()) && Byte.valueOf("0").equals(project.getIsMasterBorrower()));
            // 标记产品类型为 债转标
            if (Byte.valueOf("2").equals(projectInvestOrder.getInvestType())) {
                // 计息日期：个人标/企业标取满标日期，债转标取购买日期
                responseDTO.setCalInterTime(projectInvestOrder.getCreateTime());
                // 标记产品类型为 债转标
                responseDTO.setProductType(Byte.valueOf("6"));
                CreditorSaleDetail creditorSaleDetail = creditorSaleDetailMapperExt.selectByPrimaryKeyAndSaleUserId(projectInvestOrder.getCreditorSaleDetailId(), projectInvestOrder.getCreditorSaleUserId());
                responseDTO.setRemainingDeadlineMonth(creditorSaleDetail.getRemainingDeadlineMonth() == 0 ? null : creditorSaleDetail.getRemainingDeadlineMonth());
                responseDTO.setRemainingDeadlineDay(creditorSaleDetail.getRemainingDeadlineDay() - RepaymentUtil.getOverdueDay(creditorSaleDetail.getCreateTime(), projectInvestOrder.getCreateTime()));
                responseDTO.setRemainingDeadlineDay(responseDTO.getRemainingDeadlineDay() == 0 ? null : responseDTO.getRemainingDeadlineDay());

                tradableInvestOrderService.reCalcAmount(creditorSaleDetail);
                responseDTO.setCreditorPrincipal(creditorSaleDetail.getShare());
                responseDTO.setDiscountAmount(creditorSaleDetail.getOffAmount());
                responseDTO.setAssigneeInterest(creditorSaleDetail.getSaleAmount().subtract(creditorSaleDetail.getShare()).add(creditorSaleDetail.getOffAmount()));
            } else {
                responseDTO.setDeadline(projectInvestOrder.getDeadline());
                responseDTO.setCalInterTime(project.getFullSuccessTime());
                responseDTO.setAddRate(project.getActivityRaiseRate());
            }
            BigDecimal packageActivityRaiseRate = null;
            if(Byte.valueOf("3").equals(projectInvestOrder.getInvestType())) {
                ProjectPackageInvestOrderDetail investOrderDetail = projectPackageInvestOrderDetailMapperExt.selectByInvestOrderId(projectInvestOrderId);
                if(investOrderDetail != null){
                    ProjectPackageInvestOrder packageInvestOrder = projectPackageInvestOrderMapperExt.selectByPrimaryKey(investOrderDetail.getPackageInvestOrderId());
                    if(packageInvestOrder != null){
                        packageActivityRaiseRate = packageInvestOrder.getActivityRaiseRate();
                        responseDTO.setAddRate(packageActivityRaiseRate);
                    }
                }
            }
            responseDTO.setProductTypeDesc(Byte.valueOf("7").equals(responseDTO.getProductType()) ? "极速贷" : LoanTypeEnum.enumOf(responseDTO.getProductType()).getDesc());
            // 头像/昵称: 个人标/企业标，取借款人头像和昵称；债转标，取转让人头像和昵称
            setHeadImgAndNickName(projectInvestOrder, project.getBorrowerType(), null, responseDTO);
            responseDTO.setAmount(projectInvestOrder.getAmount());
            responseDTO.setDeadlineUnit(projectInvestOrder.getDeadlineUnit());

            responseDTO.setBorrowRate(projectInvestOrder.getBorrowRate());
            responseDTO.setStatus(projectInvestOrder.getEvolutionStatus());
            // 已提前结清
            if (Integer.valueOf(ProjectSubStatusEnum.FINISH_ADVANCE.getSubStatus()).equals(project.getSubStatus())
                    && ProjectInvestOrderEvolutionStatusEnum.ALL_BACKED.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                responseDTO.setStatus((byte) 8);
            }
            responseDTO.setRepaymentType(projectInvestOrder.getRepaymentType());
            responseDTO.setPrize(projectInvestOrder.getPrizeName());
            // 提交时间
            responseDTO.setSubmitTime(projectInvestOrder.getCreateTime());

            if (ProjectInvestOrderEvolutionStatusEnum.INVESTING.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                // 募集剩余时间：流标时间-当前时间
                Long time = project.getInvestEndTime().getTime() - new Date().getTime();
                responseDTO.setRemainRecuitTime(time < 0 ? 0 : time);
                // 待满标金额：合同金额 - 已投金额
                BigDecimal contractAmount = project.getContractAmount();
                BigDecimal investedAmount = project.getInvestedAmount();
                responseDTO.setFullScaleAmount(contractAmount.subtract(investedAmount));
                responseDTO.setIsCanInvest(responseDTO.getFullScaleAmount().compareTo(BigDecimal.ZERO) > 0 ? Byte.valueOf("0") : Byte.valueOf("1"));

                BigDecimal investInterest = BigDecimal.ZERO;
                List<RepaymentPlanDTO> repaymentPlan = RepaymentPlanContext.getRepaymentPlan(com.niiwoo.tripod.base.plan.support.RepaymentTypeEnum.enumOf(project.getRepaymentType()), project.getType(),
                        projectInvestOrder.getAmount(), project.getBorrowRate(), project.getDeadline(), PeriodUnitEnum.enumOf(project.getDeadlineUnit()), new Date());
                for (RepaymentPlanDTO repaymentPlanDTO : repaymentPlan) {
                    investInterest = investInterest.add(repaymentPlanDTO.getInterest());
                }
                // 参考收益：预期利息+预期加息
                responseDTO.setReferenceIncome(projectInvestOrder.getInterest().add(projectInvestOrder.getAddInterest()));
                // 预期利息
                responseDTO.setInterest(investInterest);
                // 平台或活动加息
                responseDTO.setPlatformAddInterest(projectInvestOrder.getInterest().subtract(investInterest)); // 投资订单利息字段包含投资利息与平台或活动加息
                // 加息券加息
                responseDTO.setPrizeAddInterest(projectInvestOrder.getAddInterest());
            } else if (ProjectInvestOrderEvolutionStatusEnum.CLOSED.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                responseDTO.setEndTime(projectInvestOrder.getUpdateTime());
                responseDTO.setOrderCloseTime(projectInvestOrder.getUpdateTime());
                // 订单关闭原因
                responseDTO.setMessage(projectInvestOrder.getClosedReason() == null ? InvestOrderCloseReasonEnum.INVEST_OVERTIME.getDesc() : InvestOrderCloseReasonEnum.enumOf(projectInvestOrder.getClosedReason()).getDesc());
                responseDTO.setPrize(responseDTO.getPrize() != null ? responseDTO.getPrize() + "(已返还)" : null);
                responseDTO.setRicevutoAmount(BigDecimal.ZERO);
                responseDTO.setReferenceIncome(BigDecimal.ZERO);

                // 参考收益：预期利息+预期加息
                responseDTO.setReferenceIncome(BigDecimal.ZERO);
                // 预期利息
                responseDTO.setInterest(BigDecimal.ZERO);
                // 已收罚息
                responseDTO.setPenaltyFee(BigDecimal.ZERO);
                // 平台或活动加息
                responseDTO.setPlatformAddInterest(BigDecimal.ZERO);
                // 加息券加息
                responseDTO.setPrizeAddInterest(BigDecimal.ZERO);
            } else if (ProjectInvestOrderEvolutionStatusEnum.BACKING.getValue().equals(projectInvestOrder.getEvolutionStatus())
                    || ProjectInvestOrderEvolutionStatusEnum.BACKING_OVERDUE.getValue().equals(projectInvestOrder.getEvolutionStatus())
                    || ProjectInvestOrderEvolutionStatusEnum.ALL_BACKED.getValue().equals(projectInvestOrder.getEvolutionStatus())
                    || ProjectInvestOrderEvolutionStatusEnum.IN_TRANSFER.getValue().equals(projectInvestOrder.getEvolutionStatus())
                    || ProjectInvestOrderEvolutionStatusEnum.TRANSFERRED.getValue().equals(projectInvestOrder.getEvolutionStatus())
                    || Byte.valueOf("8").equals(projectInvestOrder.getEvolutionStatus())) {

                InvestorCreditor investorCreditor = investorCreditorMapperExt.queryInvestorCreditorByInvestOrderId(projectInvestOrder.getId());

                // 到期日期：订单最后一次预计回款日期
                responseDTO.setExpireTime(investorCreditor.getExpectOverDate());
                // 总回款期数
                responseDTO.setTotalRepayPeriods(investorCreditor.getTotalPeriod());
                // 当前期数
                responseDTO.setCurrentPeriod(investorCreditor.getCurrentPeriod());
                // 预计回款日期
                responseDTO.setRepayTime(investorCreditor.getReceivedDate());

                if (ProjectInvestOrderEvolutionStatusEnum.BACKING.getValue().equals(projectInvestOrder.getEvolutionStatus())
                        || ProjectInvestOrderEvolutionStatusEnum.BACKING_OVERDUE.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                    // 当前期还款计划
                    BigDecimal currentPeriodAddInterest = BigDecimal.ZERO; //当前期加息
                    ProjectInvestorPlan currentPeriodPlan = projectInvestorPlanMapper.getCurrentPlanByInvestOrderId(projectInvestOrder.getId());
                    currentPeriodAddInterest = currentPeriodAddInterest.add(this.getPrizeCurrentPeriodAddInterest(projectInvestOrder, currentPeriodPlan.getCurrentPeriod()));
                    currentPeriodAddInterest = currentPeriodAddInterest.add(this.getProjectActivityCurrentPeriodAddInterest(project.getActivityRaiseRate(), projectInvestOrder.getId(), currentPeriodPlan.getCurrentPeriod()));
                    if(packageActivityRaiseRate != null){
                        currentPeriodAddInterest = currentPeriodAddInterest.add(this.getProjectActivityCurrentPeriodAddInterest(packageActivityRaiseRate, projectInvestOrder.getId(), currentPeriodPlan.getCurrentPeriod()));
                    }
                    responseDTO.setRepayAmount(currentPeriodPlan.getCapital().add(currentPeriodPlan.getInterest()).add(currentPeriodAddInterest));

                    // 若当期存在部分已回款，应收金额取原预计回款金额，已收金额取当期实际回款金额
                    if (currentPeriodPlan.getReceivedCapital().compareTo(BigDecimal.ZERO) > 0
                            || currentPeriodPlan.getReceivedInterest().compareTo(BigDecimal.ZERO) > 0
                            || currentPeriodPlan.getReceivedPenaltyFee().compareTo(BigDecimal.ZERO) > 0) {

                        responseDTO.setCurrentTotalAmount(currentPeriodPlan.getCapital().add(currentPeriodPlan.getInterest()).add(currentPeriodAddInterest));
                        responseDTO.setCurrentRepayAmount(currentPeriodPlan.getReceivedCapital().add(currentPeriodPlan.getReceivedInterest()));
                        
                        if(currentPeriodPlan.getReceivedInterest().compareTo(BigDecimal.ZERO) > 0){
                            responseDTO.setCurrentRepayAmount(responseDTO.getCurrentRepayAmount().add(currentPeriodAddInterest));
                        }
                        responseDTO.setRepayAmount(responseDTO.getCurrentTotalAmount().subtract(responseDTO.getCurrentRepayAmount()));

                        //  如果本金利息已收，状态为未结清。罚息未收完。前端需要展示待收罚息
                        if (InvestorPlanReceivedStatusEnum.NON_RECEIVE.getCode().equals(currentPeriodPlan.getReceivedStatus())
                                && currentPeriodPlan.getReceivedCapital().compareTo(currentPeriodPlan.getCapital()) == 0
                                && currentPeriodPlan.getReceivedInterest().compareTo(currentPeriodPlan.getInterest()) == 0
                                && currentPeriodPlan.getReceivedPenaltyFee().compareTo(currentPeriodPlan.getTotalPenaltyFee()) < 0) {
                            responseDTO.setCurrentTotalAmount(responseDTO.getCurrentTotalAmount().add(currentPeriodPlan.getTotalPenaltyFee()));
                            responseDTO.setCurrentRepayAmount(responseDTO.getCurrentRepayAmount().add(currentPeriodPlan.getReceivedPenaltyFee()));
                            responseDTO.setRepayAmount(currentPeriodPlan.getTotalPenaltyFee().subtract(currentPeriodPlan.getReceivedPenaltyFee()));
                        }
                    }
                }

                BigDecimal receivedAddInterest = BigDecimal.ZERO; // 已收加息
                BigDecimal recentlyAddInterest = BigDecimal.ZERO; // 待收加息

                // 标加息
                if(project.getActivityRaiseRate() != null && project.getActivityRaiseRate().compareTo(BigDecimal.ZERO) > 0){
                    recentlyAddInterest = recentlyAddInterest.add(intelligenceOrderService.getProjectActivityCurrentPeriodAddInterest(project.getActivityRaiseRate(), projectInvestOrder.getId(), Byte.valueOf("0")));
                    receivedAddInterest = receivedAddInterest.add(intelligenceOrderService.getProjectActivityCurrentPeriodAddInterest(project.getActivityRaiseRate(), projectInvestOrder.getId(), Byte.valueOf("2")));
                }
                // 加息劵
                if(projectInvestOrder.getPrizeId() != null && UserPrizeTypeIdEnum.INVESTMENT_RAISE_INTEREST_RATES.getPrizeType().equals(projectInvestOrder.getPrizeTypteId())){
                    recentlyAddInterest = recentlyAddInterest.add(intelligenceOrderService.getPrizeCurrentPeriodAddInterest(projectInvestOrder.getPrizeId(), projectInvestOrder.getProjectId(), Byte.valueOf("0")));
                    receivedAddInterest = receivedAddInterest.add(intelligenceOrderService.getPrizeCurrentPeriodAddInterest(projectInvestOrder.getPrizeId(), projectInvestOrder.getProjectId(), Byte.valueOf("2")));
                }
                // 包加息
                if(packageActivityRaiseRate != null && packageActivityRaiseRate.compareTo(BigDecimal.ZERO) > 0){
                    recentlyAddInterest = recentlyAddInterest.add(intelligenceOrderService.getProjectActivityCurrentPeriodAddInterest(packageActivityRaiseRate, projectInvestOrder.getId(), Byte.valueOf("0")));
                    receivedAddInterest = receivedAddInterest.add(intelligenceOrderService.getProjectActivityCurrentPeriodAddInterest(packageActivityRaiseRate, projectInvestOrder.getId(), Byte.valueOf("2")));
                }

                responseDTO.setTotalRepayPriInter(investorCreditor.getCapital().add(investorCreditor.getInterest()).subtract(investorCreditor.getReceivedCapital()).subtract(investorCreditor.getReceivedInterest()).add(recentlyAddInterest));
                // 实际收益=已收利息+已收罚息+实收加息
                BigDecimal repayInterest = investorCreditor.getReceivedInterest().add(investorCreditor.getReceivedPenaltyFee()).add(receivedAddInterest);
                responseDTO.setReferenceIncome(repayInterest);
                // 该订单的实收金额(本金+已收利息+已收罚息+实收加息)
                responseDTO.setRicevutoAmount(investorCreditor.getReceivedCapital().add(repayInterest));
                if (ProjectInvestOrderEvolutionStatusEnum.TRANSFERRED.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                    responseDTO.setTransferAmount(responseDTO.getRicevutoAmount());
                    responseDTO.setTotalRepayPriInter(BigDecimal.ZERO);
                }
                if (ProjectInvestOrderEvolutionStatusEnum.IN_TRANSFER.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                    // 转让金额
                    Optional.ofNullable(creditorSaleDetailMapperExt.getAppliedSuccessfullyOrderByUserIdAndInvestOrderId(projectInvestOrder.getUserId(), projectInvestOrder.getId()))
                            .ifPresent(creditorSaleDetail -> {
                                responseDTO.setTransferAmount(creditorSaleDetail.getSaleAmount().add(creditorSaleDetail.getSellingInterest()));
                                responseDTO.setTotalRepayPriInter(responseDTO.getTransferAmount());
                            });
                }
                if (ProjectInvestOrderEvolutionStatusEnum.ALL_BACKED.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                    responseDTO.setEndTime(investorCreditor.getOverTime());
                } else if (ProjectInvestOrderEvolutionStatusEnum.TRANSFERRED.getValue().equals(projectInvestOrder.getEvolutionStatus())) {
                    responseDTO.setEndTime(investorCreditor.getTransferTime());
                }

                // 参考收益：预期利息+预期加息
                responseDTO.setReferenceIncome(projectInvestOrder.getInterest().add(projectInvestOrder.getAddInterest()));
                // 预期利息
                responseDTO.setInterest(investorCreditor.getInterest());
                // 平台或活动加息
                responseDTO.setPlatformAddInterest(projectInvestOrder.getInterest().subtract(investorCreditor.getInterest())); // 投资订单利息字段包含投资利息与平台或活动加息
                // 加息券加息
                responseDTO.setPrizeAddInterest(projectInvestOrder.getAddInterest());

                if(ProjectInvestOrderEvolutionStatusEnum.ALL_BACKED.getValue().equals(projectInvestOrder.getEvolutionStatus())
                        || ProjectInvestOrderEvolutionStatusEnum.TRANSFERRED.getValue().equals(projectInvestOrder.getEvolutionStatus())){

                    StatisticUserBillAmountRequestDTO statisticUserBillAmountRequestDTO = new StatisticUserBillAmountRequestDTO();
                    List<BillAmountStatisticsEnum> billAmountStatisticsEnums = Arrays.asList(BillAmountStatisticsEnum.ACCEPTED_INTEREST,
                            BillAmountStatisticsEnum.PENALTY_INTEREST,
                            BillAmountStatisticsEnum.PLATFORM_AND_ACTIVITY_INCREASE_INTEREST,
                            BillAmountStatisticsEnum.CARD_AND_REDPACKET_INVEST,
                            BillAmountStatisticsEnum.CARD_INCREASE_INTEREST,
                            BillAmountStatisticsEnum.INVEST_CASHBACK);
                    statisticUserBillAmountRequestDTO.setUserId(projectInvestOrder.getUserId());
                    statisticUserBillAmountRequestDTO.setInvestId(projectInvestOrder.getId());
                    statisticUserBillAmountRequestDTO.setBillAmountStatisticsEnums(billAmountStatisticsEnums);

                    List<StatisticUserBillAmountReponseDTO> receivedStatistic = userBillStatisticsDubboService.statisticUserBillAmounts(statisticUserBillAmountRequestDTO);

                    BigDecimal interest = BigDecimal.ZERO;
                    BigDecimal penaltyFee = BigDecimal.ZERO;
                    BigDecimal platformAddInterest = BigDecimal.ZERO;
                    BigDecimal prizeAddInterest = BigDecimal.ZERO;
                    for (StatisticUserBillAmountReponseDTO statisticUserBillAmountReponseDTO: receivedStatistic) {
                        if(statisticUserBillAmountReponseDTO != null) {
                            if(BillAmountStatisticsEnum.ACCEPTED_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
                                interest = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
                            }
                            if(BillAmountStatisticsEnum.PLATFORM_AND_ACTIVITY_INCREASE_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
                                platformAddInterest = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
                            }
                            if(BillAmountStatisticsEnum.PENALTY_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
                                penaltyFee = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
                            }
                            if(BillAmountStatisticsEnum.CARD_INCREASE_INTEREST.equals(statisticUserBillAmountReponseDTO.getBillAmountStatisticsEnum())){
                                prizeAddInterest = statisticUserBillAmountReponseDTO.getAmount() == null ? BigDecimal.ZERO : statisticUserBillAmountReponseDTO.getAmount();
                            }

                        }
                    }

                    // 参考收益：预期利息+预期加息
                    responseDTO.setReferenceIncome(investorCreditor.getReceivedInterest().add(penaltyFee).add(platformAddInterest).add(prizeAddInterest));
                    // 已收利息
                    responseDTO.setInterest(investorCreditor.getReceivedInterest());
                    // 已收罚息
                    responseDTO.setPenaltyFee(penaltyFee);
                    // 平台或活动加息
                    responseDTO.setPlatformAddInterest(platformAddInterest);
                    // 加息券加息
                    responseDTO.setPrizeAddInterest(prizeAddInterest);

                    responseDTO.setRicevutoAmount(projectInvestOrder.getAmount().add(responseDTO.getReferenceIncome()));
                }
            }
            responseDTO.setContractAmount(project.getContractAmount());
            responseDTO.setCreditorSaleDetailId(projectInvestOrder.getCreditorSaleDetailId());
            responseDTO.setCreditorSaleUserId(projectInvestOrder.getCreditorSaleUserId());
            responseDTO.setIsShowProjectGroup((!Byte.valueOf("6").equals(responseDTO.getProductType())) && !ProjectTypeEnum.ORG_SPEEDLOAN_NEW.getValue().equals(project.getType()));
            // 暖心借展示项目群入口
            if(ProjectTypeEnum.ORG_SPEEDLOAN_NEW.getValue().equals(project.getType()) && OrgConstant.NIWOTA_ORG_ID.equals(project.getOrgId())){
                responseDTO.setIsShowProjectGroup(true);
            }
        }
        return responseDTO;
    }

    public InvestOrderMaxandMinDateResponseDTO getMyInvestOrderMaxandMinDate(String userId, Byte type) {
        return projectInvestOrderMapper.getMyInvestOrderMaxandMinDate(userId, type, Byte.valueOf("0"));
    }

    public InvestOrderMaxandMinDateResponseDTO getMyInvestOrderMaxandMinDate(String userId, Byte type, Byte queryType) {
        return projectInvestOrderMapper.getMyInvestOrderMaxandMinDate(userId, type, queryType);
    }

    public BigDecimal getMaxRate() {
        BigDecimal orgRate = organizationDubboService.getMaxOrgRate();
        BigDecimal rate = rateConfigMapper.getMaxRateConfig();
        if (orgRate == null) {
            orgRate = BigDecimal.ZERO;
        } else {
            // 机构入库时利率没做处理，这里除以100后返回
            orgRate = orgRate.divide(new BigDecimal("100"));
        }
        if (rate == null) {
            rate = BigDecimal.ZERO;
        }
        if (orgRate.compareTo(rate) == 1) {
            return orgRate;
        } else {
            return rate;
        }
    }

    public BigDecimal getPrizeCurrentPeriodAddInterest(ProjectInvestOrder projectInvestOrder, Integer currentPeriod) {
        logger.info("InvestOrderService.getPrizeCurrentPeriodAddInterest:projectInvestOrder={},currentPeriod={}", JSON.toJSON(projectInvestOrder), currentPeriod);
        BigDecimal addInterest = BigDecimal.ZERO;
        // 投资加息券
        if (projectInvestOrder.getPrizeId() != null && UserPrizeTypeIdEnum.INVESTMENT_RAISE_INTEREST_RATES.getPrizeType().equals(projectInvestOrder.getPrizeTypteId())) {
            List<InvestorExtraDetailDTO> investorExtraDetailDTOList = activityPrizeDubboService.getInvestorExtralDtlSingle(projectInvestOrder.getPrizeId());
            logger.info("InvestOrderService.getPrizeCurrentPeriodAddInterest:investorExtraDetailDTOList={}", JSON.toJSON(investorExtraDetailDTOList));
            if (investorExtraDetailDTOList != null) {
                for (InvestorExtraDetailDTO investorExtraDetailDTO : investorExtraDetailDTOList) {
                    if (investorExtraDetailDTO != null && projectInvestOrder.getProjectId().equals(investorExtraDetailDTO.getProjectId())
                            && currentPeriod.equals(investorExtraDetailDTO.getCurrPeriods())) {
                        addInterest = investorExtraDetailDTO.getExtraAmount();
                    }
                }
            }
        }
        logger.info("InvestOrderService.getPrizeCurrentPeriodAddInterest:addInterest={}", addInterest);
        return addInterest;
    }

    public BigDecimal getProjectActivityCurrentPeriodAddInterest(BigDecimal activityRaiseRate, Long investOrderId, Integer currentPeriod) {
        logger.info("InvestOrderService.getProjectActivityCurrentPeriodAddInterest:BigDecimal={},activityRaiseRate={},currentPeriod={}", activityRaiseRate, investOrderId, currentPeriod);
        BigDecimal addInterest = BigDecimal.ZERO;
        // 投资加息券
        if (activityRaiseRate != null && activityRaiseRate.compareTo(BigDecimal.ZERO) > 0) {
            List<InvestorExtraDetailDTO> investorExtraDetailDTOList = activityPrizeDubboService.getProjectAddInterest(investOrderId);
            logger.info("InvestOrderService.getProjectActivityCurrentPeriodAddInterest:investorExtraDetailDTOList={}", JSON.toJSON(investorExtraDetailDTOList));
            if (investorExtraDetailDTOList != null) {
                for (InvestorExtraDetailDTO investorExtraDetailDTO : investorExtraDetailDTOList) {
                    if (investorExtraDetailDTO != null && currentPeriod.equals(investorExtraDetailDTO.getCurrPeriods())) {
                        addInterest = investorExtraDetailDTO.getExtraAmount();
                    }
                }
            }
        }
        logger.info("InvestOrderService.getProjectActivityCurrentPeriodAddInterest:addInterest={}", addInterest);
        return addInterest;
    }


    /**
     * 获取合同信息
     *
     * @param orderId
     * @param userId
     * @return
     */
    public InvestProtocolloResponseDTO queryInvestProtocollo(Long orderId, String userId) {
        InvestProtocolloResponseDTO dto = new InvestProtocolloResponseDTO();
        ProjectInvestOrder investOrder = projectInvestOrderMapper.selectByPrimaryKey(orderId);
        Project project = projectMapper.selectByPrimaryKey(investOrder.getProjectId());
        Set<Long> projectIds = new HashSet<>();
        projectIds.add(investOrder.getProjectId());
        //居间借款合同
        List<ProjectContract> contracts = projectContractMapperExt.queryFastLoanContractByProjectIdSet(projectIds);
        if (CollectionUtils.isNotEmpty(contracts)) {
            dto.setLoanContractUrl(contracts.get(0).getViewUrl());
        }
        dto.setBorrowerType(project.getBorrowerType());
        dto.setProjectId(project.getProjectId());
        dto.setBorrowerUserId(project.getBorrowUserId());
        dto.setType(project.getType());
        dto.setOrgId(project.getOrgId());
        dto.setDeadlineUnit(project.getDeadlineUnit());
        Byte userRole = Byte.valueOf("1");

        //投资人角色
        if (Byte.valueOf("1").equals(investOrder.getInvestorType())) {
            ProjectContract contract = projectContractMapperExt.queryProjectContractByUserIdAndProjectIdAndContractType(userId, investOrder.getProjectId(), TemplateTypeEnum.RISK_PROMPT.getType());
            if (Objects.nonNull(contract)) {
                dto.setRiskAgreementUrl(contract.getViewUrl());
            }
        }

        Long contractProjectId = null;
        String creditorSaleDetailUserId = userId;
        CreditorSaleDetail creditorSaleDetail = null;
        //转让人申请转让中或已转让
        if (ProjectInvestOrderEvolutionStatusEnum.IN_TRANSFER.getValue().equals(investOrder.getEvolutionStatus()) ||
                ProjectInvestOrderEvolutionStatusEnum.TRANSFERRED.getValue().equals(investOrder.getEvolutionStatus())) {
            //债权转让人身份
            userRole = Byte.valueOf("2");
            creditorSaleDetail = creditorSaleDetailMapperExt.getAppliedSuccessfullyOrderByUserIdAndInvestOrderId(investOrder.getUserId(), investOrder.getId());
            if (creditorSaleDetail != null) {
                contractProjectId = creditorSaleDetail.getId();
            }
        } else if (Byte.valueOf("2").equals(investOrder.getInvestorType())) {
            //债权受让人身份
            userRole = Byte.valueOf("3");
            contractProjectId = investOrder.getCreditorSaleDetailId();
            creditorSaleDetailUserId = investOrder.getCreditorSaleUserId();
            creditorSaleDetail = creditorSaleDetailMapperExt.selectByPrimaryKeyAndSaleUserId(contractProjectId, creditorSaleDetailUserId);
        }

        //默认普通投资人
        dto.setUserRole(userRole);
        if (Byte.valueOf("1").equals(userRole)) {
            return dto;//普通投资者 无以下合同
        }
        //出让人或受让人 债权转让服务风险提示书
        ProjectContract contractRiskAgreement = projectContractMapperExt.queryProjectContractByUserIdAndProjectIdAndContractType(creditorSaleDetailUserId, contractProjectId, TemplateTypeEnum.CREDITOR_TRANSFER_RISK_PROMPT.getType());
        if (Objects.nonNull(contractRiskAgreement)) {
            dto.setCreditorRiskAgreementUrl(contractRiskAgreement.getViewUrl());
        } else {
            String riskAgreementUrl = creditorRiskAgreementUrl;
            if (Byte.valueOf("3").equals(userRole)) {
                riskAgreementUrl += String.format(ProtocolloUrlEnum.CREDITOR_AGREEMENT_RISK_AGREEMENT.getParam(), investOrder.getCreditorSaleDetailId(), investOrder.getCreditorSaleUserId());
            }
            dto.setCreditorRiskAgreementUrl(riskAgreementUrl);
        }
        //出让人或受让人  债权转让协议
        ProjectContract contractCreditorAgreement = projectContractMapperExt.queryProjectContractByUserIdAndProjectIdAndContractType(creditorSaleDetailUserId, contractProjectId, TemplateTypeEnum.CREDITOR_TRANSFER_PROTOCOL.getType());
        if (Objects.nonNull(contractCreditorAgreement)) {
            dto.setCreditorAgreementUrl(contractCreditorAgreement.getViewUrl());
        } else {
            if (Byte.valueOf("2").equals(userRole)) {
                tradableInvestOrderService.reCalcAmount(creditorSaleDetail);
                BigDecimal sellingInterest = Objects.isNull(creditorSaleDetail.getSellingInterest()) ? BigDecimal.ZERO : creditorSaleDetail.getSellingInterest();
                dto.setCreditorAgreementUrl(creditorAgreementUrl + String.format(ProtocolloUrlEnum.CREDITOR_AGREEMENT_BY_TRANSFEROR.getParam(), orderId, creditorSaleDetail.getSaleAmount().add(sellingInterest)));
            } else if (Byte.valueOf("3").equals(userRole)) {
                dto.setCreditorAgreementUrl(creditorAgreementUrl + String.format(ProtocolloUrlEnum.CREDITOR_AGREEMENT_BY_ASSIGNEE.getParam(), investOrder.getCreditorSaleDetailId(), investOrder.getCreditorSaleUserId()));
            }
        }

        return dto;
    }

    /**
     * 公司名称打码
     *
     * @param companyName
     * @return
     */
    private static String maskCompanyName(String companyName) {
        if (StringUtils.isBlank(companyName) || companyName.length() <= 4) {
            return companyName;
        }
        return companyName.substring(0, 2) + "***" + companyName.substring(companyName.length() - 2, companyName.length());
    }

    /**
     * 获取还款计划
     *
     * @param requestDTO
     * @return
     */
    public PageResponseDTO<ProjectBorrowerPlanResponseDTO> getPlanByProjectId(ProjectBorrowerPlanRequestDTO requestDTO) {
        PageResponseDTO<ProjectBorrowerPlanResponseDTO> pageResponseDTO = new PageResponseDTO<>();
        List<ProjectBorrowerPlanResponseDTO> responseDTOList = new ArrayList<>();

        Integer count = projectBorrowerPlanMapper.selectByProjectIdNum(requestDTO.getProjectId());
        List<ProjectBorrowerPlanNewDTO> projectBorrowerPlans = projectBorrowerPlanMapper.selectByProjectIdForAmountPage(requestDTO);

        if (projectBorrowerPlans.size() > 0) {
            for (ProjectBorrowerPlanNewDTO p : projectBorrowerPlans) {
                ProjectBorrowerPlanResponseDTO responseDTO = new ProjectBorrowerPlanResponseDTO();
                responseDTO.setCurrentPeriod(p.getPeriod());
                responseDTO.setCapital(p.getCapital());
                responseDTO.setInterest(p.getInterest());
                responseDTO.setRepaymentAmount(p.getCapital().add(p.getInterest()));
                responseDTO.setRefundDate(p.getRefundDate());
                responseDTO.setRefundStatus(p.getStatus());
                responseDTOList.add(responseDTO);
            }
        }

        pageResponseDTO.setItems(responseDTOList);
        pageResponseDTO.measureTotalPage(count, requestDTO.getPageSize());
        return pageResponseDTO;
    }

    public List<ProjectInvestOrderDTO> getInvestOrderListForActivity(InvestOrderListForActivityRequestDTO requestDTO) {
        List<ProjectInvestOrderDTO> projectInvestOrderDTOList = Lists.newArrayList();
        List<ProjectInvestOrder> projectInvestOrderList = projectInvestOrderMapper.selectInvestOrderListForActivty(requestDTO.getUserId(), requestDTO.getBeginTime(), requestDTO.getEndTime());
        for (ProjectInvestOrder projectInvestOrder : projectInvestOrderList) {
            ProjectInvestOrderDTO projectInvestOrderDTO = new ProjectInvestOrderDTO();
            projectInvestOrderDTO.setInvestOrderId(projectInvestOrder.getId());
            projectInvestOrderDTO.setProjectId(projectInvestOrder.getProjectId());
            projectInvestOrderDTO.setUserId(projectInvestOrder.getUserId());
            projectInvestOrderDTO.setInvestAmount(projectInvestOrder.getAmount());
            projectInvestOrderDTO.setInvestTime(projectInvestOrder.getCreateTime());
            projectInvestOrderDTO.setRepaymentType(projectInvestOrder.getRepaymentType());
            projectInvestOrderDTO.setDeadline(projectInvestOrder.getDeadline());
            projectInvestOrderDTO.setDeadlineUnit(projectInvestOrder.getDeadlineUnit());
            projectInvestOrderDTO.setIfFull(projectInvestOrder.getIsFull());
            projectInvestOrderDTOList.add(projectInvestOrderDTO);
        }
        return projectInvestOrderDTOList;
    }

    /**
     * 我的投资金额统计的待收本息
     * 查询产品类型：0全部、1智能投、2散标、4转让区
     *
     * @param requestDTO 请求dto
     * @return InvestAmountStatisticsResponseDTO
     */
    public InvestAmountStatisticsResponseDTO myInvestAmountStatistics(InvestAmountStatisticsRequestDTO requestDTO) {
        logger.info("myInvestAmountStatistics userId:{}, queryType={}", requestDTO.getUserId(), requestDTO.getQueryType());

        InvestAmountStatisticsResponseDTO responseDTO = new InvestAmountStatisticsResponseDTO();
         
        BigDecimal todayReceivable = getTodayReturnMoney(requestDTO);
        responseDTO.setTodayReceivable(todayReceivable);
        List<UserRelatedAmountDTO> userRelatedAmountDTOList = projectInvestorPlanMapper.queryUserNotReceivedAmountByUserId(requestDTO.getUserId(), requestDTO.getQueryType());
        if(userRelatedAmountDTOList.isEmpty()) {
            return responseDTO;
        }

        BigDecimal dueInCorpus = BigDecimal.ZERO;
        BigDecimal dueInInterest = BigDecimal.ZERO;

        BigDecimal dueInPrizeAddInterest = BigDecimal.ZERO;
        BigDecimal dueInProjectAddInterest = BigDecimal.ZERO;
        BigDecimal dueInPackageAddInterest = BigDecimal.ZERO;

        Set<Long> investOrderIdSet = new HashSet<>();

        for (UserRelatedAmountDTO userRelatedAmountDTO : userRelatedAmountDTOList) {
            dueInCorpus = dueInCorpus.add(userRelatedAmountDTO.getRecentlyCapital());
            dueInInterest = dueInInterest.add(userRelatedAmountDTO.getRecentlyInterest());
            investOrderIdSet.add(userRelatedAmountDTO.getInvestOrderId());
        }

        // 待收投资订单不为空
        if (!investOrderIdSet.isEmpty()) {
            List<ProjectInvestOrder> investOrderList = projectInvestOrderMapper.selectByInvestOrderIds(investOrderIdSet);
            SummarizeAmountRespDTO interestRates = this.summarizePrizeAmount(requestDTO.getUserId(), UserPrizeTypeIdEnum.INVESTMENT_RAISE_INTEREST_RATES.getPrizeType(), investOrderList);
            if (interestRates != null) {
                dueInPrizeAddInterest = interestRates.getToReceivedAmount();
            }

            // 非债转标才需要计算标的加息
            if (!Byte.valueOf("4").equals(requestDTO.getQueryType())) {
                List<Long> projectInvestOrderIdList = projectInvestorPlanMapper.queryProjectAddInterestInvestOrderId(requestDTO.getUserId(), requestDTO.getQueryType());
                if (!projectInvestOrderIdList.isEmpty()) {
                    SummarizeAmountRespDTO respDTO = this.summarizeProjectAddInterestAmount(requestDTO.getUserId(), projectInvestOrderIdList);
                    dueInProjectAddInterest = respDTO.getToReceivedAmount();
                }
            }

            // 包加息(查询智能投和全部时才有包加息)
            if (Byte.valueOf("1").equals(requestDTO.getQueryType()) || Byte.valueOf("0").equals(requestDTO.getQueryType())) {
                List<Long> packageInvestOrderIdList = projectInvestorPlanMapper.queryPackageAddInterestInvestOrderIdByUserId(requestDTO.getUserId());
                if (!packageInvestOrderIdList.isEmpty()) {
                    SummarizeAmountRespDTO respDTO = this.summarizeProjectAddInterestAmount(requestDTO.getUserId(), packageInvestOrderIdList);
                    dueInPackageAddInterest = respDTO.getToReceivedAmount();
                }
            }

            logger.info("myInvestAmountStatistics userId:{}, queryType={}, dueInInterest:{}, dueInPrizeAddInterest:{}, dueInProjectAddInterest:{}, dueInPackageAddInterest:{}",
                    requestDTO.getUserId(), requestDTO.getQueryType(), dueInInterest.toPlainString(), dueInPrizeAddInterest.toPlainString(),
                    dueInProjectAddInterest.toPlainString(), dueInPackageAddInterest.toPlainString());

            responseDTO.setDueInCorpus(dueInCorpus);
            responseDTO.setReferenceInterest(dueInInterest.add(dueInPrizeAddInterest).add(dueInProjectAddInterest).add(dueInPackageAddInterest));
            responseDTO.setDueInCorpusInterest(responseDTO.getDueInCorpus().add(responseDTO.getDueInCorpusInterest()).add(responseDTO.getReferenceInterest()));
        }
        logger.info("myInvestAmountStatistics userId:{}, queryType={}, responseDTO:{}", requestDTO.getUserId(), requestDTO.getQueryType(), JSON.toJSON(responseDTO));
        return responseDTO;
    }

    /**
     * 根据用户ID获取今日待收金额
     */
    public BigDecimal getTodayReturnMoney(InvestAmountStatisticsRequestDTO requestDTO) {
        Date receivedDate = DateUtils.parseDateFromString(FastDateFormat.getInstance(DateUtils.SHOW_DATE_FORMAT).format(new Date()), DateUtils.SHOW_DATE_FORMAT);
        List<UserTodayRelatedAmountDTO> userTodayRelatedAmountDTOList = projectInvestorPlanMapper.getTodayReturnMoneyByUserId(requestDTO.getUserId(), receivedDate);
        if(userTodayRelatedAmountDTOList.isEmpty()){
            return BigDecimal.ZERO;
        }

        BigDecimal todayReturnMoney = BigDecimal.ZERO;
        List<ProjectRaiseAddInterestReqDTO.ProjectRaisePlanReqDTO> projectAddInterestList = new ArrayList<>();
        List<PrizeAddInterestReqDTO.ProjectPrizeReqDTO> projectPrizeList = new ArrayList<>();

        Set<Long> intelligenceInvestOrderIdSet = new HashSet<>();
        
        for(UserTodayRelatedAmountDTO userTodayRelatedAmountDTO : userTodayRelatedAmountDTOList){
            if(userTodayRelatedAmountDTO.getActivityRaiseRate() != null && userTodayRelatedAmountDTO.getActivityRaiseRate().compareTo(BigDecimal.ZERO) > 0){
                ProjectRaiseAddInterestReqDTO.ProjectRaisePlanReqDTO reqDTO = new ProjectRaiseAddInterestReqDTO.ProjectRaisePlanReqDTO();
                reqDTO.setInvestOrderId(userTodayRelatedAmountDTO.getInvestOrderId());
                reqDTO.setCurrentPeriod(userTodayRelatedAmountDTO.getCurrentPeriod());
                projectAddInterestList.add(reqDTO);
            }
            if(userTodayRelatedAmountDTO.getPrizeId() != null && UserPrizeTypeIdEnum.INVESTMENT_RAISE_INTEREST_RATES.getPrizeType().equals(userTodayRelatedAmountDTO.getPrizeTypteId())){
                PrizeAddInterestReqDTO.ProjectPrizeReqDTO reqDTO = new PrizeAddInterestReqDTO.ProjectPrizeReqDTO();
                reqDTO.setProjectId(userTodayRelatedAmountDTO.getProjectId());
                reqDTO.setPrizeId(userTodayRelatedAmountDTO.getPrizeId());
                reqDTO.setCurrentPeriod(userTodayRelatedAmountDTO.getCurrentPeriod());
                projectPrizeList.add(reqDTO);
            }
            todayReturnMoney = todayReturnMoney.add(userTodayRelatedAmountDTO.getCapital().add(userTodayRelatedAmountDTO.getInterest()))
                    .subtract(userTodayRelatedAmountDTO.getReceivedCapital()).subtract(userTodayRelatedAmountDTO.getReceivedInterest());

            if (Byte.valueOf("3").equals(userTodayRelatedAmountDTO.getInvestType())) { //智能投
                intelligenceInvestOrderIdSet.add(userTodayRelatedAmountDTO.getInvestOrderId());
            }
        }

        // 标的加息
        if(!projectAddInterestList.isEmpty()){
            ProjectRaiseAddInterestReqDTO reqDTO = new ProjectRaiseAddInterestReqDTO();
            reqDTO.setUserId(requestDTO.getUserId());
            reqDTO.setInvestOrderList(projectAddInterestList);
            ProjectAddInterestSummarizeRespDTO projectAddInterest = activityPrizeDubboService.findProjectRaiseAddInterestInfo(reqDTO);
            logger.info("getTodayReturnMoney.findProjectRaiseAddInterestInfo reqDTO={}, projectAddInterest:{}", JSON.toJSON(reqDTO), JSON.toJSON(projectAddInterest));
            if(projectAddInterest != null && projectAddInterest.getUnreceivedAmount() != null){
                todayReturnMoney = todayReturnMoney.add(projectAddInterest.getUnreceivedAmount());
            }
        }

        //投资加息劵
        if(!projectPrizeList.isEmpty()){
            PrizeAddInterestReqDTO prizeReqDTO = new PrizeAddInterestReqDTO();
            prizeReqDTO.setUserId(requestDTO.getUserId());
            prizeReqDTO.setProjectPrizeList(projectPrizeList);
            ProjectAddInterestSummarizeRespDTO prizeAddInterest = activityPrizeDubboService.findProjectPrizeAddInterestInfo(prizeReqDTO);
            logger.info("getTodayReturnMoney.findProjectPrizeAddInterestInfo prizeReqDTO={}, prizeAddInterest:{}", JSON.toJSON(prizeReqDTO), JSON.toJSON(prizeAddInterest));
            if(prizeAddInterest != null && prizeAddInterest.getUnreceivedAmount() != null){
                todayReturnMoney = todayReturnMoney.add(prizeAddInterest.getUnreceivedAmount());
            }
        }

        // 包加息
        if(!intelligenceInvestOrderIdSet.isEmpty()) {
            List<ProjectInvestorPlan> projectInvestorPlanList = projectInvestorPlanMapper.queryPackageAddInterestInvestorPlanByInvestOrderIdSet(intelligenceInvestOrderIdSet, receivedDate);
            if (!projectInvestorPlanList.isEmpty()) {
                List<ProjectRaiseAddInterestReqDTO.ProjectRaisePlanReqDTO> packageAddInterestList = new ArrayList<>();
                projectInvestorPlanList.forEach(plan -> {
                    ProjectRaiseAddInterestReqDTO.ProjectRaisePlanReqDTO reqDTO = new ProjectRaiseAddInterestReqDTO.ProjectRaisePlanReqDTO();
                    reqDTO.setCurrentPeriod(plan.getCurrentPeriod());
                    reqDTO.setInvestOrderId(plan.getInvestOrderId());
                    packageAddInterestList.add(reqDTO);
                });

                ProjectRaiseAddInterestReqDTO reqDTO = new ProjectRaiseAddInterestReqDTO();
                reqDTO.setUserId(requestDTO.getUserId());
                reqDTO.setInvestOrderList(packageAddInterestList);
                ProjectAddInterestSummarizeRespDTO packageAddInterest = activityPrizeDubboService.findProjectRaiseAddInterestInfo(reqDTO);
                logger.info("getTodayReturnMoney.findProjectRaiseAddInterestInfo reqDTO={}, packageAddInterest:{}", JSON.toJSON(reqDTO), JSON.toJSON(packageAddInterest));
                if (packageAddInterest != null && packageAddInterest.getUnreceivedAmount() != null) {
                    todayReturnMoney = todayReturnMoney.add(packageAddInterest.getUnreceivedAmount());
                }
            }
        }
        return todayReturnMoney;
    }

    // 标的加息
    public SummarizeAmountRespDTO summarizeProjectAddInterestAmount(String userId, List<Long> investOrderIdList) {
        logger.info("summarizeProjectAddInterestAmount userId={}, investOrderIdList={}", userId, JSON.toJSON(investOrderIdList));
        SummarizeProjectAddInterestAmountReqDTO reqDTO = new SummarizeProjectAddInterestAmountReqDTO();
        reqDTO.setUserId(userId);
        reqDTO.setInvestOrderIdList(investOrderIdList);
        SummarizeAmountRespDTO respDTO = activityPrizeDubboService.summarizeProjectAddInterestAmount(reqDTO);
        logger.info("summarizeProjectAddInterestAmount respDTO={}", JSON.toJSONString(respDTO));
        return respDTO;
    }

    // 加息券/投资返现红包
    private SummarizeAmountRespDTO summarizePrizeAmount(String userId, Byte prizeTypeId, List<ProjectInvestOrder> investOrderList) {
        logger.info("summarizePrizeAmount userId={}, prizeTypeId={}, investOrderListSize={}", userId, prizeTypeId, investOrderList.size());
        List<Long> prizeIdList = new ArrayList<>();
        investOrderList.forEach(investOrder -> {
            if (investOrder.getPrizeId() != null && investOrder.getPrizeTypteId() != null
                    && prizeTypeId.equals(investOrder.getPrizeTypteId())) {
                prizeIdList.add(investOrder.getPrizeId());
            }
        });
        SummarizeAmountRespDTO respDTO = null;
        if (prizeIdList.size() > 0) {
            SummarizePrizeAmountReqDTO reqDTO = new SummarizePrizeAmountReqDTO();
            reqDTO.setUserId(userId);
            reqDTO.setPrizeIdList(prizeIdList);
            reqDTO.setPrizeTypeId(prizeTypeId);
            respDTO = activityPrizeDubboService.summarizePrizeAmount(reqDTO);
        }
        logger.info("summarizePrizeAmount respDTO={}", JSON.toJSONString(respDTO));
        return respDTO;
    }

    /**
     * 查询智能投合同
     * @param requestDTO 请求dto
     * @return InvestProtocolloResponseDTO
     */
    public InvestProtocolloResponseDTO queryIntelligenceInvestProtocollo(IntelligenceProtocolloRequestDTO requestDTO) {
        logger.info("queryIntelligenceInvestProtocollo requestDTO={}", JSON.toJSONString(requestDTO));
        InvestProtocolloResponseDTO responseDTO = new InvestProtocolloResponseDTO();
        ProjectPackageInvestOrder packageInvestOrder = projectPackageInvestOrderMapperExt.selectByPrimaryKey(requestDTO.getPackageInvestOrderId());
        if(packageInvestOrder != null){
            List<Byte> contractTypeList = new ArrayList<>();
            contractTypeList.add(FadadaContractTemplateEnum.TemplateTypeEnum.INTELLIGENCE_RISK_PROMPT.getType());
            contractTypeList.add(FadadaContractTemplateEnum.TemplateTypeEnum.INTELLIGENT_SERVICE_PROTOCOL.getType());

            List<ProjectContract> projectContractList = projectContractMapperExt.queryIntelligenceInvestProtocollo(requestDTO.getUserId(),packageInvestOrder.getPackageId(), contractTypeList);
            projectContractList.forEach(projectContract -> {
                if(projectContract.getViewUrl() != null &&
                        FadadaContractTemplateEnum.TemplateTypeEnum.INTELLIGENCE_RISK_PROMPT.getType().equals(projectContract.getContractType())){
                    responseDTO.setIntelligenceRiskContractUrl(projectContract.getViewUrl());
                }else if(projectContract.getViewUrl() != null
                        && FadadaContractTemplateEnum.TemplateTypeEnum.INTELLIGENT_SERVICE_PROTOCOL.getType().equals(projectContract.getContractType())){
                    responseDTO.setIntelligentContractUrl(projectContract.getViewUrl());
                }
            });
        }
        if(responseDTO.getIntelligenceRiskContractUrl() == null){
            responseDTO.setIntelligenceRiskContractUrl(this.intelligenceInvestRiskUrl);
        }else if(responseDTO.getIntelligentContractUrl() == null){
            responseDTO.setIntelligentContractUrl(this.intelligenceInvestAgreementUrl);
        }
        return responseDTO;
    }


    public ProjectInvestOrder getInvestByInvestOrderId(Long investOrderId) {
        ProjectInvestOrder projectInvestOrder = projectInvestOrderMapper.selectByPrimaryKey(investOrderId);
        if (projectInvestOrder == null) {
            logger.info("getInvestByInvestOrderId:{}查询无结果", investOrderId);
            return null;
        }
        return projectInvestOrder;
    }

    public Long getInvestIdByRefundDetailId(Long refundDetailId) {
        Assert.notNull(refundDetailId, "参数不可空");
        // 1：根据orderId查询t_tc_refund_order_detail，获取detail_request_no
        RefundOrderDetail refundOrderDetail = refundOrderDetailMapperExt.selectByPrimaryKey(refundDetailId);
        String detailRequestNo = refundOrderDetail.getDetailRequestNo();
        // 2 : 根据detail_request_no查询t_tc_refund_order_detail_biz，获取biz表的back_plan_id
        RefundOrderDetailBiz refundOrderDetailBiz = refundOrderDetailBizMapperExt.getRefundOrderDetailBizByDetailRequestNo(detailRequestNo);
        Long backPlanId = refundOrderDetailBiz.getBackPlanId();
        // 3：根据back_plan_id查询t_tc_project_investor_plan，获取invest_order_id
        ProjectInvestorPlan investorPlan = projectInvestorPlanMapper.selectByPrimaryKey(backPlanId);
        return investorPlan.getInvestOrderId();
    }

    public ProjectInvestOrder selectFristInvestProject(String userId) {
        return projectInvestOrderMapper.selectFirstInvestByUser(userId);
    }
}
